<?php

class SQLFile {

	protected $pdoh;

	function __construct($pdo) {
		$this->pdoh = $pdo;
	}
	
	static function start() {
		ob_start();
	}
	
	static function end() {
		$var = ob_get_contents();
		ob_end_clean();
		return $var;
	}
	
	static function load($sqlfile, $params = null) {
		if( is_array($params) ) extract( $params );
		if( file_exists( APP_PATH . "/sql/$sqlfile.sql.php" ) )
			return include( APP_PATH . "/sql/$sqlfile.sql.php" );
		elseif( file_exists( SYSTEM_PATH . "/sql/$sqlfile.sql.php" ) )
			return include( SYSTEM_PATH . "/sql/$sqlfile.sql.php" );
		else throw new Exception("SQL could not be loaded", JF_Exception::SQL_COULD_NOT_BE_LOADED );
	}

	/**
	 *
	 * @param PDOStatement $pdos
	 * @param array $params
	 */
	static function prepare($pdos, $params) {
		foreach( $params as $param => $value ) {
			if( is_string( $value ) ) $pdos->bindValue(':'.$param, $value, PDO::PARAM_STR);
			elseif( is_null( $value ) ) $pdos->bindValue(':'.$param, $value, PDO::PARAM_NULL);
			elseif( is_int( $value ) ) $pdos->bindValue(':'.$param, $value, PDO::PARAM_INT);
			elseif( is_bool( $value ) ) $pdos->bindValue(':'.$param, $value, PDO::PARAM_BOOL);
			else $pdos->bindValue(':'.$param, $value, PDO::PARAM_STR);
		}
	}
	/**
	 *
	 * @param string $sqlfile
	 * @param array $params
	 * @return PDOStatement
	 */
	function loadAndPrepare($sqlfile, $params = array(), $otherParams = array() ) {
		$sql = self::load( $sqlfile, array_merge($params, $otherParams) );
		$pdos = $this->pdoh->prepare( $sql );
		if( isset( $params ) ) self::prepare($pdos, $params);
		return $pdos;
	}

	

}